package com.zkool.train.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zkool.train.entity.TrainNumber;
import com.zkool.train.entity.TrainStation;
import com.zkool.train.entity.TrainTimetable;
import com.zkool.train.exception.ServiceException;
import com.zkool.train.repository.TrainNumberRepository;
import com.zkool.train.repository.TrainStationRepository;
import com.zkool.train.repository.TrainTimetableRepository;
import com.zkool.train.util.TrainUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by zhaokui on 2019/8/11.
 */
@Service
public class TrainServiceImpl implements TrainService {

    @Value("${train.search-no}")
    private String trainSearchNo;

    @Value("${train.search-no-station}")
    private String trainSearchNoStation;

    @Value("${amap.restapi}")
    private String amapRestapi;

    @Autowired
    private TrainNumberRepository trainNumberRepository;
    @Autowired
    private TrainStationRepository trainStationRepository;
    @Autowired
    private TrainTimetableRepository trainTimetableRepository;


    @Override
    @Transactional
    public TrainNumber getOrSaveTrainNumber(String code) {
        TrainNumber trainNumber = trainNumberRepository.findByCode(code);
        if(trainNumber != null){
            return trainNumber;
        }

        JSONObject trainNumberJson = TrainUtil.getTrainNo(trainSearchNo, code);
        if(trainNumberJson == null || trainNumberJson.getString("train_no") == null){
            throw new ServiceException("未获取到车次信息");
        }

        JSONArray trainStationJsonArray = TrainUtil.getTrainStation(trainSearchNoStation, trainNumberJson.getString("train_no"));
        if(trainStationJsonArray == null){
            throw new ServiceException("未获取到车次站点信息");
        }

        //存车次
        trainNumber = saveTrainNumber(trainNumberJson);
        List<TrainTimetable> trainTimetableList = new ArrayList<TrainTimetable>();
        for (Iterator iterator = trainStationJsonArray.iterator(); iterator.hasNext();) {
            JSONObject trainStationJsonObj = (JSONObject) iterator.next();

            if(trainStationJsonObj.getString("station_name") == null){
                throw new ServiceException("解析车次站点信息异常");
            }

            //取/存站点
            TrainStation trainStation = trainStationRepository.findByName(trainStationJsonObj.getString("station_name"));
            if(trainStation == null){
                trainStation = saveTrainStation(trainStationJsonObj.getString("station_name"));
            }
            TrainTimetable trainTimetable = saveTrainTimetable(trainNumber, trainStation, trainStationJsonObj);
            trainTimetable.setTrainStation(trainStation);
            trainTimetableList.add(trainTimetable);
        }
        trainNumber.setTrainTimetableList(trainTimetableList);
        return trainNumber;

    }

    public TrainNumber saveTrainNumber(JSONObject trainNumberJson){
        TrainNumber trainNumber = new TrainNumber();
        trainNumber.setCode(trainNumberJson.getString("station_train_code"));
        trainNumber.setNo(trainNumberJson.getString("train_no"));
        trainNumber.setFromStation(trainNumberJson.getString("from_station"));
        trainNumber.setToStation(trainNumberJson.getString("to_station"));
        trainNumber.setTotalNum(trainNumberJson.getIntValue("total_num"));
        trainNumber.setStatus(1);
        trainNumber.setCreateTime(new Date());
        trainNumber.setUpdateTime(trainNumber.getCreateTime());
        return trainNumberRepository.save(trainNumber);
    }

    public TrainStation saveTrainStation(String name){
        JSONObject geoCodeJson = TrainUtil.geoCode(amapRestapi, name+"站");
        if(geoCodeJson == null){
            throw new ServiceException("未获取到站点【" + name + "】的地理编码信息");
        }

        TrainStation trainStation = new TrainStation();
        trainStation.setName(name);
        trainStation.setCountry(geoCodeJson.getString("country"));
        trainStation.setProvince(geoCodeJson.getString("province"));
        trainStation.setCity(geoCodeJson.getString("city"));
        trainStation.setCityCode(geoCodeJson.getString("citycode"));
        trainStation.setDistrict(geoCodeJson.getString("district"));
        trainStation.setTownship(geoCodeJson.getString("township"));

        String location = geoCodeJson.getString("location");
        if(location != null && location.contains(",")){
            String[] locationArr = location.split(",");
            trainStation.setLng(locationArr[0]);
            trainStation.setLat(locationArr[1]);
        }else{
            throw new ServiceException("未获取到站点【" + name + "】的经纬度");
        }

        trainStation.setStatus(1);
        trainStation.setCreateTime(new Date());
        trainStation.setUpdateTime(trainStation.getCreateTime());
        return trainStationRepository.save(trainStation);
    }

    public TrainTimetable saveTrainTimetable(TrainNumber trainNumber, TrainStation trainStation, JSONObject trainStationJsonObj){
        TrainTimetable trainTimetable = new TrainTimetable();
        trainTimetable.setTrainNumber(trainNumber);
        trainTimetable.setTrainStation(trainStation);
        trainTimetable.setOrderNum(trainStationJsonObj.getInteger("station_no"));
        trainTimetable.setArriveTime(trainStationJsonObj.getString("arrive_time"));
        trainTimetable.setArriveTimeFlag(trainStationJsonObj.getString("arrive_day_diff"));
        trainTimetable.setStartTime(trainStationJsonObj.getString("start_time"));
        trainTimetable.setRunningTime(trainStationJsonObj.getString("running_time"));
        trainTimetable.setStatus(1);
        trainTimetable.setCreateTime(new Date());
        trainTimetable.setUpdateTime(trainTimetable.getCreateTime());
        return trainTimetableRepository.save(trainTimetable);
    }



}
